package cn.enited.devtools.apiaggregator.config;

import cn.enited.devtools.apiaggregator.api.cache.ApiCacheManager;
import cn.enited.devtools.apiaggregator.api.cache.BiCacheManager;
import cn.enited.devtools.apiaggregator.api.cache.CacheSyncManager;
import cn.enited.devtools.apiaggregator.api.cache.listener.RedisSetCmdListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.support.collections.RedisSet;

import java.io.Serializable;


/**
 * Created by wwk on 2020/11/12.
 */
@Configuration
public class RedisConfig {

    private RedisConnectionFactory redisConnectionFactory;

    private RedisSetCmdListener redisSetCmdListener;

    @Autowired
    public void setRedisConnectionFactory(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public ApiCacheManager apiCacheManager() {
        return new BiCacheManager(redisTemplate());
    }

    @Bean
    public CacheSyncManager cacheSyncManager() {
        return new CacheSyncManager(apiCacheManager());
    }

    @Bean
    public RedisSetCmdListener redisSetCmdListener() {
        return new RedisSetCmdListener(cacheSyncManager());
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 监听key set事件
        RedisSetCmdListener redisSetCmdListener = redisSetCmdListener();
        container.addMessageListener(redisSetCmdListener, redisSetCmdListener.getPatternTopic());
        return container;
    }
}
